import moment from 'moment';
import {ElMessage as Message} from 'element-plus';
import Storage from "@/utils/storage";
import {USER_INFO_KEY} from "@/utils/enums/cache-enum";

const user = Storage.get(USER_INFO_KEY)
const organizationCode = user.organizationCode;
/**
 * 根据当前角色 返回当前机构的 播放逻辑
 * */
export const getPlayRule = () => {
  if (organizationCode === 'lexiang') {
    return lxPlayRule;
    /* eslint-disable */
  } else if (organizationCode === 'xxjly') {
    return xinxingPlayRule;
  } else {
    return defaultPlayRule;
  }
};

/**
 * 声音最终播放函数
 * 注：该函数仅会被voice函数调用
 * */
let isPlayApk = true;
const _play = (voice: any) => {
  console.error('开始播放', voice);
  return new Promise((resolve) => {
    // debugger
    const message = voice.alarmText || '';
    // &time=${alarmTime}
    let uri = `https://voice.langzhiyun.net/configure/voice/loadVoice?content=${message}&language=cn`;
    if (isPlayApk) {
      try {
        /* eslint-disable */
        const win: any = window
        const injected = win.injected
        injected?.playAudio(uri);
        return;
      } catch (e) {
        // debugger
        isPlayApk = false;
        console.log('app音频播放失败');
      }
    }

    if (!isPlayApk) {
      let audio = new Audio();
      audio.src = uri;
      let playPromise = audio.play();
      if (playPromise !== undefined) {
        playPromise
          .then(() => {
            /* 监听语音是否播报完成 */
            audio.addEventListener(
              'ended',
              function () {
                voice.lastTime = new Date().getTime();
                voice.lastTimeFormat = moment(voice.lastTime).format('hh:mm:ss');
                resolve(true);
              },
              false,
            );
          })
          .catch((e) => {
            if (e.toString().includes('https://goo.gl/xX8pDD')) {
              Message.warning({
                dangerouslyUseHTMLString: true,
                duration: 0,
                showClose: true,
                message: `<p style="color:red;">您的浏览器被限制声音自动播放</p> <p style="margin-top: 10px">1.请F5刷新重新尝试</p><p style="margin-top: 10px">2.浏览器设置开始声音播放</p>`,
              });
            } else {
              console.error(e);
              debugger;
            }
          });
      }
    }
  });
};
/**
 * 乐享播放规则（重复播放 没有时间间隔）
 * */
export const lxPlayRule = (voice: any) => {
  console.log('当前声音', voice);
  console.log(voice.id + `上一次播报时间`, moment(voice.lastTime).format('hh:mm:ss'));
  return new Promise(async (resolve) => {
    const res = await _play(voice);
    if (res === true) {
      resolve(true);
    }
  });
};
/**
 * 默认机构播放规则(报警5分钟内只报一次)
 * */
export const defaultPlayRule = (voice: any) => {
  console.log('当前声音', voice);
  console.log(voice.alarmText + `上一次播报时间`, moment(voice.lastTime).format('hh:mm:ss'));
  return new Promise(async (resolve) => {
    const timeDiff = (new Date().getTime() - voice.lastTime) / 1000;
    console.log(`${JSON.stringify(voice.alarmText)}时间差--`, moment(timeDiff).format('hh:mm:ss'));
    if (voice.lastTime === 0) {
      // 首次播放
      // 首次(首次直接播放，非首次则下次播放，避免冷却时间到后 前后衔接问题  重复播报两次)
      const res = await _play(voice);
      if (res === true) {
        resolve(true);
        console.error(`首次播放 完成`);
      }
    } else if (timeDiff > 300) {
      // 播放间隔大于5分钟
      // debugger
      console.log(`播放间隔大于5分钟`);
      const res = await _play(voice);
      if (res === true) {
        resolve(true);
      }
    } else {
      console.log(voice.alarmText + `冷却时间`);
      resolve(true);
    }
  });
};

/**
 * 新兴卫生院语音播报  特殊逻辑
 * */
export const xinxingPlayRule = (voice = {lastTime: 0}) => {
  console.log('xinxing当前声音', voice);
  return new Promise(async (resolve) => {
    // if (voice.alarmType === '30') {
    // debugger
    const timeDiff = (new Date().getTime() - voice.lastTime) / 1000;
    console.log(`新兴卫生院时间间隔`, timeDiff);
    if (voice.lastTime === 0 || timeDiff > 60) {
      const res = await pollingPlay(voice);
      // debugger
      if (res === true) {
        resolve(true);
      }
    } else if (timeDiff < 60) {
      // debugger
      resolve(true);
    }
    // } else {
    //   console.log(`新兴卫生院 非sos设备  播报一次`);
    //   const res = await _play(voice);
    //   if (res === true) {
    //     resolve(true);
    //   }
    // }
  });
};
// 循环播放十次
const pollingPlay = (voice: any) => {
  return new Promise((resolve) => {
    let count = 0;
    const awaitPlay = async () => {
      // 播放十次结束递归
      if (count >= 3) {
        resolve(true);
        return;
      }
      const status = await _play(voice);
      if (status) {
        count++;
      }
      console.log(`新兴卫生院count`, count);
      awaitPlay();
    };
    awaitPlay();
  });
};
